package orm

import (
	"gorm.io/gorm"
)

type QueryBuilder struct {
	Db            *gorm.DB
	Tx            *gorm.DB
	Conditions    map[string]interface{} `json:"_where"`
	Order         []string               `json:"_order"`
	Page          int                    `json:"page"`
	Limit         int                    `json:"limit"`
	joinCount     int
	joinLinkCount int
	joinsAlis     map[string]string //eg:user=t_1
	Root          *EzModelConfig
}

func NewQueryBuilder(db *gorm.DB, root *EzModelConfig) (qb *QueryBuilder) {

	qb = new(QueryBuilder)
	qb.Root = root
	qb.Db = db
	qb.Conditions = make(map[string]interface{})
	qb.Order = make([]string, 0)
	qb.joinsAlis = make(map[string]string)
	qb.Tx = qb.Db.Session(&gorm.Session{DryRun: false}).Table(qb.Root.GetTableName())
	return qb
}

func (this *QueryBuilder) Prepare(where map[string]interface{}, order []string, page int, Limit int) *gorm.DB {
	this.Conditions = where
	this.Order = order
	this.Limit = Limit
	this.Page = page
	this.CreateConditions()
	this.CreateOrders()
	tx := this.Tx.Limit(this.Limit).Offset((this.Page - 1) * this.Limit)
	return tx
}
